Online PHP Function(s){ #Test PHP functions online!; }

  •  
 

 
Added: 08/10/2012 by John

Simple MySQL PDO implementation class

There are many ways to use MySQL. This is a class I use on some of my projects, very simple, allows me to use the same connection all over the project using a static variable.
<?php
class sql
{
    public static 
$db false;
    private 
$database_host '127.0.0.1';
    private 
$database_user 'username';
    private 
$database_pass 'verySecretPassWord';
    private 
$database_db 'database';

    function 
__construct()
    {
        if (
self::$db === false) {
            
$this->connect();
        }
    }

    private function 
connect()
    {
        
$dsn $this->database_type ":dbname=" $this->database_db ";host=" $this->database_host;
        try {
            
self::$db = new PDO($dsn$this->database_user$this->database_pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
            
self::$db->setAttribute(PDO::ATTR_ERRMODEPDO::ERRMODE_EXCEPTION);
        } catch (
PDOException $e) {
            
            
//your log handler
        
}
    }

}

Usage

Usage is very simple, some examples:

Select using prepared statement

<?php
$q 
sql::$db->prepare("SELECT id, name FROM `users` WHERE `username` = ?");
$q -> execute( array( $_POST['username'] ) ); //Yes, you can use the raw userinput without sanitizing!
while( $r $q->fetch) ){
    echo 
$r['id'];
}
                    

Simple update query

<?php
$q 
sql::$db->query("UPDATE `users` SET `last_login` = ".time()." WHERE `id` = ".(int)$userId); 

Prepared statement update

<?php
$q 
sql::$db->prepare("UPDATE `users` SET `username` = ? WHERE `id` = ? "
            
->execute( array( $userName$userId);

Prepared statement insert

<?php
$q 
sql::$db->prepare("INSERT INTO `users` SET `username` = ? , `password` = ?"
            
->execute( array( $userNamesha1($password.$salt));


 

 

 


Comments

 
 
      © 2019 OnlinePHPFunctions.com | Disclaimer |       PHP versions: 7.2.4, 7.1.0, 7.0.14, 7.0.5, 7.0.4, 7.0.3, 7.0.2, 7.0.1, 5.6.29, 5.6.20, 5.6.19, 5.6.18, 5.6.17, 5.6.2, 5.5.34, 5.5.33, 5.5.32, 5.5.31, 5.5.18, 5.5.5, 5.5.0.a6, 5.5.0.a.5, 5.5.0.a.2, 5.4.34, 5.4.21, 5.4.13, 5.4.12, 5.4.11, 5.4.10, 5.4.9, 5.4.8, 5.4.7, 5.4.6, 5.4.5, 5.4.4, 5.4.3, 5.4.2, 5.4.1, 5.4.0, 5.3.29, 5.3.27, 5.3.23, 5.3.22, 5.3.21, 5.3.20, 5.3.19, 5.3.18, 5.3.17, 5.3.16, 5.3.15, 5.3.14, 5.3.13, 5.3.12, 5.3.11, 5.3.10, 5.3.2, 5.3.1, 5.3.0, 5.2.17, 5.2.16, 5.1.6, 5.1.5, 5.0.5, 5.0.4, 4.4.9